#!/bin/bash

# ES Archive 部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查依赖..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装"
        exit 1
    fi
    
    # 检查kubectl（如果部署到Kubernetes）
    if [[ "$DEPLOY_TARGET" == "kubernetes" ]] && ! command -v kubectl &> /dev/null; then
        log_error "kubectl未安装"
        exit 1
    fi
    
    log_info "依赖检查完成"
}

# 构建Docker镜像
build_image() {
    log_info "构建Docker镜像..."
    
    docker build -f Dockerfile.es-archive -t es-archive:latest .
    
    if [[ $? -eq 0 ]]; then
        log_info "Docker镜像构建成功"
    else
        log_error "Docker镜像构建失败"
        exit 1
    fi
}

# Docker部署
deploy_docker() {
    log_info "使用Docker Compose部署..."
    
    # 创建必要的目录
    mkdir -p ./data/{backups,metadata,logs}
    mkdir -p ./config
    
    # 复制配置文件
    if [[ ! -f ./config/config.yaml ]]; then
        log_info "创建默认配置文件..."
        cat > ./config/config.yaml << EOF
elasticsearch:
  hosts: ["elasticsearch:9200"]
  timeout: 60

backup:
  default_strategy: "full"
  batch_size: 1000
  compression: "gzip"
  parallel_workers: 4

storage:
  root_path: "/data"
  max_storage_size: "100GB"
  retention_days: 30

monitoring:
  enable_metrics: true
  collection_interval: 5.0
EOF
    fi
    
    # 启动服务
    docker-compose -f docker-compose.es-archive.yml up -d
    
    if [[ $? -eq 0 ]]; then
        log_info "Docker部署成功"
        log_info "Elasticsearch: http://localhost:9200"
        log_info "Grafana: http://localhost:3000 (admin/admin)"
        log_info "Prometheus: http://localhost:9090"
    else
        log_error "Docker部署失败"
        exit 1
    fi
}

# Kubernetes部署
deploy_kubernetes() {
    log_info "部署到Kubernetes..."
    
    # 创建命名空间
    kubectl apply -f deploy/kubernetes/configmap.yaml
    
    # 创建存储
    kubectl apply -f deploy/kubernetes/storage.yaml
    
    # 部署应用
    kubectl apply -f deploy/kubernetes/deployment.yaml
    
    # 等待部署完成
    log_info "等待Pod启动..."
    kubectl wait --for=condition=ready pod -l app=es-archive -n es-archive --timeout=300s
    
    if [[ $? -eq 0 ]]; then
        log_info "Kubernetes部署成功"
        
        # 显示服务信息
        kubectl get pods -n es-archive
        kubectl get services -n es-archive
    else
        log_error "Kubernetes部署失败"
        exit 1
    fi
}

# 健康检查
health_check() {
    log_info "执行健康检查..."
    
    if [[ "$DEPLOY_TARGET" == "docker" ]]; then
        # Docker健康检查
        if docker-compose -f docker-compose.es-archive.yml ps | grep -q "Up"; then
            log_info "Docker服务运行正常"
        else
            log_error "Docker服务异常"
            return 1
        fi
        
        # 检查Elasticsearch
        for i in {1..30}; do
            if curl -s http://localhost:9200/_cluster/health > /dev/null; then
                log_info "Elasticsearch连接正常"
                break
            fi
            log_warn "等待Elasticsearch启动... ($i/30)"
            sleep 10
        done
        
    elif [[ "$DEPLOY_TARGET" == "kubernetes" ]]; then
        # Kubernetes健康检查
        if kubectl get pods -n es-archive | grep -q "Running"; then
            log_info "Kubernetes Pod运行正常"
        else
            log_error "Kubernetes Pod异常"
            return 1
        fi
    fi
    
    log_info "健康检查完成"
}

# 清理部署
cleanup() {
    log_info "清理部署..."
    
    if [[ "$DEPLOY_TARGET" == "docker" ]]; then
        docker-compose -f docker-compose.es-archive.yml down -v
        docker rmi es-archive:latest 2>/dev/null || true
        
    elif [[ "$DEPLOY_TARGET" == "kubernetes" ]]; then
        kubectl delete -f deploy/kubernetes/deployment.yaml
        kubectl delete -f deploy/kubernetes/storage.yaml
        kubectl delete -f deploy/kubernetes/configmap.yaml
    fi
    
    log_info "清理完成"
}

# 显示使用帮助
show_help() {
    cat << EOF
ES Archive 部署脚本

用法: $0 [选项] <命令>

命令:
  build       构建Docker镜像
  deploy      部署应用
  health      健康检查
  cleanup     清理部署
  help        显示帮助

选项:
  -t, --target TARGET    部署目标 (docker|kubernetes) [默认: docker]
  -h, --help            显示帮助

示例:
  $0 build
  $0 -t docker deploy
  $0 -t kubernetes deploy
  $0 health
  $0 cleanup

EOF
}

# 主函数
main() {
    # 默认参数
    DEPLOY_TARGET="docker"
    COMMAND=""
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -t|--target)
                DEPLOY_TARGET="$2"
                shift 2
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            build|deploy|health|cleanup|help)
                COMMAND="$1"
                shift
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 验证部署目标
    if [[ "$DEPLOY_TARGET" != "docker" && "$DEPLOY_TARGET" != "kubernetes" ]]; then
        log_error "无效的部署目标: $DEPLOY_TARGET"
        exit 1
    fi
    
    # 执行命令
    case $COMMAND in
        build)
            check_dependencies
            build_image
            ;;
        deploy)
            check_dependencies
            build_image
            if [[ "$DEPLOY_TARGET" == "docker" ]]; then
                deploy_docker
            elif [[ "$DEPLOY_TARGET" == "kubernetes" ]]; then
                deploy_kubernetes
            fi
            health_check
            ;;
        health)
            health_check
            ;;
        cleanup)
            cleanup
            ;;
        help|"")
            show_help
            ;;
        *)
            log_error "未知命令: $COMMAND"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
